package com.versita.utils;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextProvider {
    private static Logger logger = Logger.getLogger(ApplicationContextProvider.class);
    private static String fileName = null;

    private static ApplicationContext applicationContext = null;
    private static final ApplicationContextProvider INSTANCE = new ApplicationContextProvider();

    static {
        fileName = "application-context.xml";
        createApplicationContext();
    }

    public static ApplicationContextProvider getInstance() {
        return INSTANCE;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType)  {
        return getInstance().getApplicationContext().getBean(requiredType);
    }
    public static <T> T getBean(String beanName,Class<T> requiredType)  {
        return getInstance().getApplicationContext().getBean(beanName,requiredType);
    }

    public static void reset() {
        createApplicationContext();
    }

    private static void createApplicationContext() {
        try {
            logger.info("loading config from fileName " + fileName);
            applicationContext = new ClassPathXmlApplicationContext(new String[] {fileName});
        } catch (Throwable e) {
            logger.error("Exception initializing App context: " + e.getMessage(),e);
        }
    }

}
